/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.aop.aspectj.annotation;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

/**
 * {@link AspectJAwareAdvisorAutoProxyCreator} subclass that processes all AspectJ
 * annotation aspects in the current application context, as well as Spring Advisors.
 *
 * <p>Any AspectJ annotated classes will automatically be recognized, and their
 * advice applied if Spring AOP's proxy-based model is capable of applying it.
 * This covers method execution joinpoints.
 *
 * <p>If the &lt;aop:include&gt; element is used, only @AspectJ beans with names matched by
 * an include pattern will be considered as defining aspects to use for Spring auto-proxying.
 *
 * <p>Processing of Spring Advisors follows the rules established in
 * {@link org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator}.
 *
 * @author Rod Johnson
 * @author Juergen Hoeller
 * @since 2.0
 * @see org.springframework.aop.aspectj.annotation.AspectJAdvisorFactory
 */
@SuppressWarnings("serial")
/**
 * 【重要】这个是aop的核心处理器, 它是一个BeanPostProcessor, 从ioc代码可以看出, 一个bean的创建过程中先后8次使用到bpp, 这里看下
 * AnnotationAwareAspectJAutoProxyCreator在8次使用中分别的作用
 *
 * 第一次: 使用的是InstantiationAwareBeanPostProcessor, 判断是否直接生成代理对象, AnnotationAwareAspectJAutoProxyCreator
 * 继承了 AbstractAutoProxyCreator 类实现了 InstantiationAwareBeanPostProcessor接口,
 * 调用了其 postProcessBeforeInstantiation(Class<?>, String)方法
 * 【总结】这里不会生成代理对象, 走正常的bean的创建流程
 *
 * 第二次: 使用的是SmartInstantiationAwareBeanPostProcessor, 用于推断实例化bean时所采用的构造器,
 * AnnotationAwareAspectJAutoProxyCreator 继承了 AbstractAutoProxyCreator 类实现了 SmartInstantiationAwareBeanPostProcessor 接口,
 * 调用了其 determineCandidateConstructors(Class<?>, String)方法, 该方法返回null, 其不参与构造器推断
 * 【总结】 这里不参与构造器的推断
 *
 * 第三次: 使用的是MergedBeanDefinitionPostProcessor, 用于提前找到属性注入点, AnnotationAwareAspectJAutoProxyCreator
 * 没有直接或间接实现MergedBeanDefinitionPostProcessor接口, 所以这里跳过
 * 【总结】这里不会使用到当前bpp
 *
 * 第四次: 使用的是SmartInstantiationAwareBeanPostProcessor, 用于：如果在支持循环依赖的前提下, 会将实例化的bean对象,
 * 创建对应的三级缓存对象singletonFactory对象, 该对象的方法getEarlyBeanReference方法中第四次使用了BeanPostProcessor,
 * 用于提前暴露实例化但未初始化的bean
 * 【总结】 如果存在循环引用, 会提前调用 wrapIfNecessary 方法进行aop, 创建代理对象并返回
 *
 * 第五次：使用的是InstantiationAwareBeanPostProcessor, 用于判断bean是否需要属性注入, AnnotationAwareAspectJAutoProxyCreator
 * 继承了 AbstractAutoProxyCreator 类实现了 InstantiationAwareBeanPostProcessor 接口, 调用了其
 * postProcessAfterInstantiation(Object, String)方法, 该方法返回true, 表示不会阻断属性注入
 * 【总结】不会影响属性注入
 *
 * 第六次: 使用的是InstantiationAwareBeanPostProcessor, 用于bean的属性注入, AnnotationAwareAspectJAutoProxyCreator 继承了
 * AbstractAutoProxyCreator 类实现了 InstantiationAwareBeanPostProcessor 接口, 调用了其
 * postProcessProperties(PropertyValues, Object, String)方法，该方法没有作任何处理
 * 【总结】不会参与属性注入
 *
 * 第七次: 使用的是BeanPostProcessor, 在bean属性注入之后, 执行初始化方法之前, 对bean进行aop操作,
 * AnnotationAwareAspectJAutoProxyCreator 继承了 AbstractAutoProxyCreator 类实现了 BeanPostProcessor 接口,
 * 调用了其 postProcessBeforeInitialization(Object, String)方法，该方法没有作任何处理
 * 【总结】不会参与
 *
 * 第八次: 使用的是BeanPostProcessor, 在执行初始化方法之后, 对bean进行aop操作, AnnotationAwareAspectJAutoProxyCreator 继承了
 * AbstractAutoProxyCreator 类实现了 BeanPostProcessor 接口, 调用了其 postProcessBeforeInitialization(Object, String)方法,
 * 生成代理对象
 * 【总结】这里是核心, 创建aop后的代理对象
 *
 */
public class AnnotationAwareAspectJAutoProxyCreator extends AspectJAwareAdvisorAutoProxyCreator {

	@Nullable
	private List<Pattern> includePatterns;

	@Nullable
	private AspectJAdvisorFactory aspectJAdvisorFactory;

	@Nullable
	private BeanFactoryAspectJAdvisorsBuilder aspectJAdvisorsBuilder;


	/**
	 * Set a list of regex patterns, matching eligible @AspectJ bean names.
	 * <p>Default is to consider all @AspectJ beans as eligible.
	 */
	public void setIncludePatterns(List<String> patterns) {
		this.includePatterns = new ArrayList<>(patterns.size());
		for (String patternText : patterns) {
			this.includePatterns.add(Pattern.compile(patternText));
		}
	}

	public void setAspectJAdvisorFactory(AspectJAdvisorFactory aspectJAdvisorFactory) {
		Assert.notNull(aspectJAdvisorFactory, "AspectJAdvisorFactory must not be null");
		this.aspectJAdvisorFactory = aspectJAdvisorFactory;
	}

	@Override
	protected void initBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		super.initBeanFactory(beanFactory);
		if (this.aspectJAdvisorFactory == null) {
			this.aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory);
		}
		this.aspectJAdvisorsBuilder =
				new BeanFactoryAspectJAdvisorsBuilderAdapter(beanFactory, this.aspectJAdvisorFactory);
	}


	@Override
	protected List<Advisor> findCandidateAdvisors() {
		// Add all the Spring advisors found according to superclass rules.
		// 这里跳过, 一般获取的为空
		List<Advisor> advisors = super.findCandidateAdvisors();
		// Build Advisors for all AspectJ aspects in the bean factory.
		if (this.aspectJAdvisorsBuilder != null) {
			// 2.构建Advisor
			advisors.addAll(this.aspectJAdvisorsBuilder.buildAspectJAdvisors());
		}
		return advisors;
	}

	@Override
	protected boolean isInfrastructureClass(Class<?> beanClass) {
		// Previously we setProxyTargetClass(true) in the constructor, but that has too
		// broad an impact. Instead we now override isInfrastructureClass to avoid proxying
		// aspects. I'm not entirely happy with that as there is no good reason not
		// to advise aspects, except that it causes advice invocation to go through a
		// proxy, and if the aspect implements e.g the Ordered interface it will be
		// proxied by that interface and fail at runtime as the advice method is not
		// defined on the interface. We could potentially relax the restriction about
		// not advising aspects in the future.
		return (super.isInfrastructureClass(beanClass) ||
				(this.aspectJAdvisorFactory != null && this.aspectJAdvisorFactory.isAspect(beanClass)));
	}

	/**
	 * Check whether the given aspect bean is eligible for auto-proxying.
	 * <p>If no &lt;aop:include&gt; elements were used then "includePatterns" will be
	 * {@code null} and all beans are included. If "includePatterns" is non-null,
	 * then one of the patterns must match.
	 */
	protected boolean isEligibleAspectBean(String beanName) {
		if (this.includePatterns == null) {
			return true;
		}
		else {
			for (Pattern pattern : this.includePatterns) {
				if (pattern.matcher(beanName).matches()) {
					return true;
				}
			}
			return false;
		}
	}


	/**
	 * Subclass of BeanFactoryAspectJAdvisorsBuilderAdapter that delegates to
	 * surrounding AnnotationAwareAspectJAutoProxyCreator facilities.
	 */
	private class BeanFactoryAspectJAdvisorsBuilderAdapter extends BeanFactoryAspectJAdvisorsBuilder {

		public BeanFactoryAspectJAdvisorsBuilderAdapter(
				ListableBeanFactory beanFactory, AspectJAdvisorFactory advisorFactory) {

			super(beanFactory, advisorFactory);
		}

		@Override
		protected boolean isEligibleBean(String beanName) {
			return AnnotationAwareAspectJAutoProxyCreator.this.isEligibleAspectBean(beanName);
		}
	}

}
